# 贷款
from aaa.api.base_api import BaseAPI
from aaa.utils.DB import DB
from aaa.login import Login


class Loans(BaseAPI):

    def loans_get_user_id(self, data_login):
        username = data_login.get('username')
        if not username:
            raise ValueError("缺少必要的参数: username")

        db = DB()
        db.connect()  # 必须添加这一行！否则 self.cursor 是 None

        user_id = db.execute(
            "SELECT id FROM user WHERE username = %s",
            (username,)
        )
        print(user_id)
        if not user_id:
            raise ValueError(f"未找到用户名为 {username} 的用户")

        return user_id[0][0]  # 如果返回的是元组列表，请根据实际结果调整索引

    def loans(self, data_loans):
        url_loans = self.BASE_URL + '/user/applyLoan/'
        request = self.session.post(url_loans, data=data_loans)
        return self._handle_response(request, '贷款')


if __name__ == '__main__':
    # 初始化 Loans 实例，自动继承 BaseAPI 中的 session
    loans = Loans()

    # 测试数据
    data_login = {
        'username': 'user',
        'password': 'e10adc3949ba59abbe56e057f20f883e',
        'money': '100'
    }

    data_loans = {
        'amount': 1000,
        'term': 1,
        'rate': 0.1500
    }

    # 登录并保持 session
    login_result = Login(session=loans.session).login(data_login)
    print("登录结果:", login_result)

    # 发起贷款请求
    loan_result = loans.loans(data_loans)
    print("贷款结果:", loan_result)
